# coding=utf-8

import re
import urllib.request
import config
import binascii
import logging
import time
import inspect
import os
import urllib
import json
# import mq
import traceback
import pub
# from util.pyDes import *
# import database as db
# import translate.api as trans
# import util.requests as requests
import uuid
import hashlib
from datetime import datetime, timedelta
from calendar import monthrange
from subprocess import check_output, call, STDOUT
from urllib.parse import urlencode, quote
import sys
import settings

# 日志
logger = settings.get_log("pub")

# 当前目录名称
CURRENT_DIR_PATH = os.path.dirname(inspect.currentframe().f_code.co_filename)
# 获取MD5值
# logger.info(f"CURRENT_DIR_PATH: {CURRENT_DIR_PATH}")

province = {
    'AH': 'ANHUI SHENG',
    'BJ': 'BEIJING SHI',
    'CH': 'CHONGQING SHI',
    'FJ': 'FUJIAN SHENG',
    'GS': 'GANSU SHENG',
    'GD': 'GUANGDONG SHENG',
    'GX': 'GUANGXI ZHUANGZU ZIZHIQU',
    'GU': 'GUIZHOU SHENG',
    'HI': 'HAINAN SHENG',
    'HE': 'HEBEI SHENG',
    'HL': 'HEILONGJIANG SHENG',
    'HN': 'HENAN SHENG',
    'HK': 'HONG KONG (SPECIAL ADMINISTRATIVE REGION)',
    'HB': 'HUBEI SHENG',
    'HA': 'HUNAN SHENG',
    'JS': 'JIANGSU SHENG',
    'JX': 'JIANGXI SHENG',
    'JL': 'JILIN SHENG',
    'LN': 'LIAONING SHENG',
    'MO': 'MACAO (SPECIAL ADMINISTRATIVE REGION)',
    'NM': 'NEI MONGOL ZIZHIQU',
    'NX': 'NINGXIA HUIZI ZIZHIQU',
    'QH': 'QINGHAI SHENG',
    'SN': 'SHAANXI SHENG',
    'SD': 'SHANDONG SHENG',
    'SH': 'SHANGHAI SHI',
    'SX': 'SHANXI SHENG',
    'SC': 'SICHUAN SHENG',
    'TW': 'TAIWAN SHENG',
    'TJ': 'TIANJIN SHI',
    'XJ': 'XINJIANG UYGUR ZIZHIQU',
    'XZ': 'XIZANG ZIZHIQU',
    'YN': 'YUNNAN SHENG',
    'ZJ': 'ZHEJIANG SHENG'
}

def fmst(st=None, dis="01", new=1):
    """
    dis "000111" 正0 正1 负1
    """
    strs = "0123456789abcdefghijklmnopqrstuvwxyz"
    if new:
        if len(st) != len(dis) // 2:
            logger.error(f"参数长度不一致 st: {st} dis: {dis}")
        if len(st) == 1:
            s = strs.find(st[0])
            d = int(dis[:2])
            return strs[s + d] if d < 10 else strs[s - d % 10]
        else:
            return "%s%s" % (fmst(st[:-1], dis[:-2]), fmst(st[-1], dis[-2:]))
    else:
        if len(st) == 2:
            a, b = st
            i = strs.find(a)
            o = strs.find(b)
            n = i * 36 + o + dis
            x = (n) // 36
            y = (n) % 36
            # logger.info(f"i: {i}, o: {o}, x: {x}, y: {y}")
            st = strs[x] + strs[y]
        elif len(st) == 3:
            a, b, c = st
            i = strs.find(a)
            o = strs.find(b)
            x = strs.find(c)
            if dis == 1:
                st = a + strs[o - 1] + strs[x + 1]
            elif dis == 2:
                st = strs[i + 1] + strs[o - 1] + strs[x + 1]
        elif len(st) == 5:
                a = st[0]
                b = st[2]
                i = strs.find(a) + 2
                o = strs.find(b) + 1
                st = strs[i] + st[1] + strs[o] + st[3:]
        return st


def md5(str):
    return (hashlib.md5(str).hexdigest())

# 获取真实的目录
def get_real_dir(dir):
    return CURRENT_DIR_PATH + "/" + dir


# 获取当前的时间
def get_now_times():
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


# 判断字符串是否为整数
def str_isint(mystr):
    m = re.match(r'^\d+$', str(mystr))
    return m != None


# 判断是否是Email
def str_isemail(str):
    m = re.match(r"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", str)
    return m != None


# 分割字符串,去除空字符串
def str_split(str):
    arr = str.split(',')
    arr2 = []
    for i in range(0, len(arr)):
        item = arr[i].strip()
        if(item != ''):
            arr2.append(item)
    return arr2


#
def http_get(requesturl):
    try:
        req = urllib.request.Request(requesturl)
        req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Data Center; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; Avant Browser; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)")
        response = urllib.request.urlopen(req)
        responseText = response.read()
        return responseText
    except Exception as e:
        write_log("HTTP请求异常，连接：" + requesturl + "，错误信息：" + e.message)
        return ""


# 下载图片
def http_download_file(url, filename):
    try:
        urllib.urlretrieve(url, filename)
        return True
    except Exception:
        return False



# DES加密
def des_encrypt(encryptString, encryptKey):
    k = triple_des(encryptKey, mode=ECB, pad=None, padmode=PAD_PKCS5)
    return k.encrypt(encryptString)



# DES解密
def des_decrypt(decryptString, decryptKey):
    hexResult = binascii.unhexlify(decryptString)
    k = triple_des(decryptKey, mode=ECB, pad=None, padmode=PAD_PKCS5)
    return k.decrypt(hexResult)



# 从服务器端获取时间戳
def http_get_timestamp():
    requesturl = config.BASE_INTERFACE_URL + '/client/gettime.aspx'
    return http_get(requesturl)


# 写日志
def write_log(message):
    try:
        write_text_log(message)
    except Exception:
        logger.debug(message)


# 写日志
def log(pk, title, msg="", auto=0):
    message = "[" + str(pk) + "][" + str(title) + "]" + str(msg)
    message = message.decode('utf-8')
    try:
        # 若为开发环境，则及时输出日志到屏幕
        if(config.config.get("BASE", "IS_DEVELOP") == "True"):
            logger.info(message)
        else:
            write_text_log(message)
            write_mq_log(pk, title, msg, auto)
    except Exception:
        if(config.config.get("BASE", "IS_DEVELOP")):
            logger.info(traceback.format_exc())
        pass


# 获取现在的时间
def get_now_time(format="%Y-%m-%d %H:%M:%S"):
    return time.strftime(format, time.localtime(time.time()))


# 写文本日志
def write_text_log(message):
    try:
        filename = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        f = open(CURRENT_DIR_PATH + "/log/" + filename + "-log.txt", 'a')
        f.write("【" + time.strftime('%Y-%m-%d %H:%M:%S',
                                    time.localtime(time.time())) + "】" + str(message)+'\n')
        f.close()
    except Exception:
        pass


# 写Mq日志
def write_mq_log(pk, title, msg, auto=0):
    data = {"pk": str(pk), "title": str(title), "msg": str(msg), "time": time.strftime(
        '%Y-%m-%d %H:%M:%S', time.localtime(time.time())), "user": "", "auto": auto}
    mq.send_message("fv.logs", json.dumps(data))


# 获取正则表达式皮配值
def get_reg_value(regs, src):
    # 如果为列表，循环，以此获取正则值
    # logger.info(str(regs))
    if(isinstance(regs, list)):
        for i in range(0, len(regs)):
            # logger.info(i)
            src = get_reg_value_ex(regs[i], src)
        return src
    else:
        return get_reg_value_ex(regs, src)


# 高级的获取正则表达式的值
def get_reg_value_ex(parttern, src):
    pattern = re.compile(parttern)
    # logger.info(str(pattern))
    match = pattern.search(src)
    if match:
        # logger.info(str(match))
        return match.group()
    else:
        return ""


# 高级的获取正则表达式的值2，要两次才匹配的出来的情况
def get_reg_value_ex2(parttern1, parttern2, src):
    lst = get_reg_value_list(parttern1, src)
    # logger.info(parttern2)
    # logger.info('(?<="checkbox" name=").+?(?=".+成都-走马街)')
    for i in range(0, len(lst)):
        txt = lst[i]
        val = get_reg_value(r'' + parttern2 + r'', txt)
        if val:
            return val
    return ""


def get_reg_value_list(parttern, src):
    pattern = re.compile(parttern)
    match = pattern.findall(src)
    if match:
        return match
    else:
        return []


# 正则替换
def reg_replace(parttern, src, to):
    p = re.compile(parttern)
    return p.sub(to, src)


# 返回匹配的数量
def get_reg_match_count(parttern, src):
    pattern = re.compile(parttern)
    match = pattern.findall(src)
    return len(match)


# 根据Id获取领事馆编码
def get_consulate_code(consulate_id):
    model = db.get_one("select code from " + config.DB_PREFIX +
                       "base_consulate where id=" + str(consulate_id))
    if(model != None):
        return model['code']
    else:
        return ""


# 根据Id获取领事馆编码（预约网站）
def get_consulate_yycode(consulate_id):
    model = db.get_one("select yycode from " + config.DB_PREFIX +
                       "base_consulate where id=" + str(consulate_id))
    if(model != None):
        return model['yycode']
    else:
        return ""


# 获取洲的英文名
def get_province_name(province_id):
    if(province_id is None or province_id == '' or province_id == 0):
        return ""
    try:
        province_id = int(province_id)
    except Exception:
        return ""
    # 若为数字，则去查询，否则直接进行翻译
    if(str_isint(province_id)):
        city = db.get_one("select name from " + config.DB_PREFIX +
                          "base_province where id=" + str(province_id))
        if(city != None):
            return city['name']
        else:
            return province_id
    else:
        return province_id
# 获取城市英文名称


def get_city_name(city_id):
    if(city_id is None or city_id == '' or city_id == 0):
        return ""
    try:
        city_id = int(city_id)
    except Exception:
        return ""
    # 若为数字，则去查询，否则直接进行翻译
    if(str_isint(city_id)):
        city = db.get_one("select name from " + config.DB_PREFIX +
                          "base_city where id=" + str(city_id))
        if(city != None):
            return city['name']
        else:
            return city_id
    else:
        return city_id


# 获取洲的英文名
def get_province_name_en(province_id):
    if(province_id is None or province_id == '' or province_id == 0):
        return ""
    try:
        province_id = int(province_id)
    except Exception:
        return trans.trans_province(province_id)
    # 若为数字，则去查询，否则直接进行翻译
    if(str_isint(province_id)):
        city = db.get_one("select name_en_real from " + config.DB_PREFIX +
                          "base_province where id=" + str(province_id))
        if(city != None):
            return city['name_en_real']
        else:
            return trans.trans_province(province_id)
    else:
        return trans.trans_province(province_id)


# 获取城市英文名称
def get_city_name_en(city_id):
    if(not city_id or city_id is None or city_id == '' or city_id == 0):
        return ""
    try:
        city_id = int(city_id)
    except Exception:
        return trans.trans_city(city_id)
    # 若为数字，则去查询，否则直接进行翻译
    if(str_isint(city_id)):
        city = db.get_one("select name_en_real from " +
                          config.DB_PREFIX + "base_city where id=" + str(city_id))
        if(city != None):
            return city['name_en_real']
        else:
            return trans.trans_city(city_id)
    else:
        return trans.trans_city(city_id)


# 获取区名称
def get_district_name(district_id):
    if(not district_id):
        return ""
    try:
        district_id = int(district_id)
    except Exception:
        return district_id
    # 若为数字，则去查询，否则直接进行翻译
    if(str_isint(district_id)):
        city = db.get_one("select name from " + config.DB_PREFIX +
                          "base_district where id=" + str(district_id))
        if(city != None):
            return city['name']
        else:
            return district_id
    else:
        return district_id


# 获取区英文名称
def get_district_name_en(district_id):
    if(not district_id or district_id is None or district_id == '' or district_id == 0):
        return ""
    try:
        district_id = int(district_id)
    except Exception:
        return trans.trans_city(city_id)
    # 若为数字，则去查询，否则直接进行翻译
    if(str_isint(district_id)):
        city = db.get_one("select name_en_real from " + config.DB_PREFIX +
                          "base_district where id=" + str(district_id))
        if(city):
            return city['name_en_real']
        else:
            return trans.trans_city(district_id)
    else:
        return trans.trans_city(district_id)


def get_language_en(id):
    if(id is None or id is None):
        return ""
    field = "name_en"
    opt = db.get_one("select " + field + " from " +
                     config.DB_PREFIX + "base_language where id=" + str(id))
    if(opt is not None):
        return opt[field]
    else:
        return ""


# 获取国家基础设置英文名
def get_country_option_name_en(option_id):
    if(option_id is None or option_id == '' or option_id == 0):
        return ""
    # 若为数字，则去查询，否则直接进行翻译
    if(str_isint(option_id)):
        option = db.get_one("select name_en from " + config.DB_PREFIX +
                            "base_country_option where id=" + str(option_id))
        if(option != None):
            return option['name_en']
        else:
            return trans.trans(option_id)
    else:
        return trans.trans(option_id)


# 根据Id获取基础选项（base_option）的code
def get_base_option_code(option_id):
    if(option_id is None):
        return ""
    opt = db.get_one("select code from " + config.DB_PREFIX +
                     "base_option where id=" + str(option_id))
    if(opt is not None):
        return opt['code']
    else:
        return ""


# 根据Id获取基础选项（base_option）的code2
def get_base_option_code2(option_id):
    if(option_id is None):
        return ""
    opt = db.get_one("select code2 from " + config.DB_PREFIX +
                     "base_option where id=" + str(option_id))
    if(opt is not None):
        return opt['code2']
    else:
        return ""


# 根据Id获取基础选项（base_option）的desc
def get_base_option_desc(option_id):
    if(option_id is None):
        return ""
    opt = db.get_one("select `desc` from " + config.DB_PREFIX +
                     "base_option where id=" + str(option_id))
    if(opt != None):
        if(opt['desc']):
            return opt['desc']
        else:
            return ""
    else:
        return ""


# 获取国家编码
def get_base_country_code(id, country):
    if(id is None or country is None):
        return ""
    field = "code_" + str(country)
    opt = db.get_one("select " + field + " from " +
                     config.DB_PREFIX + "base_country where id=" + str(id))
    if(opt is not None):
        return opt[field]
    else:
        return ""


# 获取国家英文名称
def get_base_country_english_name(id):
    if(id is None):
        return ""
    field = "english_name"
    opt = db.get_one("select " + field + " from " +
                     config.DB_PREFIX + "base_country where id=" + str(id))
    if(opt is not None):
        return opt[field]
    else:
        return ""


# 获取所有的申根国列表
def get_schengen_country_list():
    return [113, 120, 158, 159, 168, 173, 174, 182, 185, 201, 202, 209, 223, 229, 230, 239, 258, 268, 279, 280, 299, 300, 306, 318, 319]


# 判断国家是否为申根国
def country_is_schengen(id):
    schengen_country_list = get_schengen_country_list()
    return id in schengen_country_list


# 给定的url下载图片文件
def download_image2(session, url):
    try:
        path = config.config.get("BASE", "TEMP_FILE_DIR")
        if(os.path.exists(path) != True):
            os.makedirs(path)
        filename = path + "/" + str(uuid.uuid1()) + ".jpg"
        filename = filename.replace('//', '/')
        with open(filename, 'wb') as handle:
            request = session.get(url, prefetch=False, verify=False)
            for block in request.iter_content(10240):
                if not block:
                    break
                handle.write(block)
            handle.close()
        return (True, filename)
    except Exception:
        logger.debug(traceback.format_exc())
        return (False, "")


# 给定的url下载图片文件
def download_image(url, path=None, headers={}):
    try:
        # 若没有给定目录，则下载到临时目录
        if(path == None):
            path = config.config.get("BASE", "TEMP_FILE_DIR")
        if(os.path.exists(path) != True):
            os.makedirs(path)
        filename = path + "/" + str(uuid.uuid1()) + ".jpg"
        filename = filename.replace('//', '/')
        with open(filename, 'wb') as handle:
            request = requests.get(url, prefetch=False,
                                   verify=False, headers=headers)
            for block in request.iter_content(10240):
                if not block:
                    break
                handle.write(block)
            handle.close()
        if os.path.exists(filename):
            return (True, filename)
        else:
            pub.log("", "下载图片失败", filename+"下载失败")
            return (False, filename)
    except Exception:
        pub.log("", "下载图片失败", traceback.format_exc())
        return (False, "")


# 保存request到的内容到文件
def save_requested_to_file(request, extention, path=None):
    try:
        # 若没有给定目录，则下载到临时目录
        if(path == None):
            path = config.config.get("BASE", "TEMP_FILE_DIR")
        if(os.path.exists(path) != True):
            os.makedirs(path)
        filename = path + "/" + str(uuid.uuid1()) + "." + extention
        filename = filename.replace('//', '/')
        with open(filename, 'wb') as handle:
            for block in request.iter_content(10240):
                if not block:
                    break
                handle.write(block)
            handle.close()
        return (True, filename)
    except Exception:
        log("", "保存request到的内容到文件", traceback.format_exc())
        return (False, "")


def get_filename_from_path(path):
    try:
        return get_reg_value(r'[^/]*$', path)
    except Exception:
        return ""


# 调用邮件服务器接口生成邮件账号
def generate_email_account(username, password, key_id=""):
    try:
        sign = md5(username + "&" + password)
        url = config.config.get("BASE", "MAIL_INTER_URL") + "/interface.php?act=useradd&username=" + \
            username + "&password=" + password + "&sign=" + sign
        succ = http_get(url)
        if(succ == "OK"):
            return True
        else:
            log(key_id, "生成Email账号失败", succ)
            return False
    except Exception:
        log(key_id, "生成Email账号异常", traceback.format_exc())
        return False


# 从服务器上根据关键字获取邮件内容
def get_email_content_from_server(username, send_time, keywords=""):
    #send_time = quote(str(send_time))
    sign = md5(username + "&" + send_time + "&" + keywords)
    # logger.info(username + "&" + send_time + "&" + keywords)
    url = config.config.get("BASE", "MAIL_INTER_URL") + "/interface.php?act=get_mail_content&username=" \
        + quote(username) + "&sendtime=" + quote(str(send_time)) + \
        "&keywords=" + keywords + "&sign=" + sign
    body = http_get(url)
    # print(url)
    return body


# 计算年龄
def age(date):
    try:
        d = date.day
        m = date.month
        y = date.year
        # get the current time in tuple format
        a = time.gmtime(time.time())
        #difference in day
        dd = a[2]-d
        #difference in month
        dm = a[1]-m
        #difference in year
        dy = a[0]-y
        # checks if difference in day is negative
        if dd < 0:
            dd = dd+30
            dm = dm-1
            # checks if difference in month is negative when difference in day is also negative
            if dm < 0:
                dm = dm+12
                dy = dy-1
        # checks if difference in month is negative when difference in day is positive
        if dm < 0:
            dm = dm+12
            dy = dy-1
        return dy
    except Exception:
        logger.debug(traceback.format_exc())
        return -1


# 计算个月数
def get_month_count(date):
    try:
        d = date.day
        m = date.month
        y = date.year
        # get the current time in tuple format
        a = time.gmtime(time.time())
        #difference in day
        dd = a[2]-d
        #difference in month
        dm = a[1]-m
        #difference in year
        dy = a[0]-y
        return dy*12+dm
    except Exception:
        logger.debug(traceback.format_exc())
        return -1


# 获取天数
def urldecode(query):
    query = query.replace('&amp;', '&')
    return query


# 发送翻译队列
def send_trans_mq(app_id, country_id):
    data = {"id": app_id, "country_id": country_id}
    mq.send_message("fv.translate", json.dumps(data))


# 日期计算
def time_add(start, type, num):
    endTime = None
    type = type.lower()
    if(type == 'y'):
        return time_add(start, 'm', 12 * num)
    elif(type == 'm'):
        if(num > 0):
            tmp = 0
            while(tmp < num):
                start = start + \
                    timedelta(days=monthrange(start.year, start.month)[1])
                tmp += 1
            endTime = start
        else:
            tmp = 0
            num = -num
            while(tmp < num):
                start = start - \
                    timedelta(days=monthrange(start.year, start.month)[1])
                tmp += 1
            endTime = start
    elif(type == 'w'):
        if(num > 0):
            endTime = start + timedelta(weeks=int(num))
        else:
            endTime = start + timedelta(weeks=-int(num))
    elif(type == 'd'):
        if(num > 0):
            endTime = start + timedelta(days=int(num))
        else:
            endTime = start - timedelta(days=-int(num))
    elif(type == 'h'):
        if(num > 0):
            endTime = start + timedelta(hours=int(num))
        else:
            endTime = start - timedelta(hours=-int(num))
    elif(type == 'i'):
        if(num > 0):
            endTime = start + timedelta(minutes=int(num))
        else:
            endTime = start - timedelta(minutes=-int(num))
    elif(type == 's'):
        if(num > 0):
            endTime = start + timedelta(seconds=int(num))
        else:
            endTime = start - timedelta(seconds=-int(num))
    return endTime


# 格式化日期
def date_format(date, format):
    if date:
        return date.strftime(format)
    else:
        return ""


# 获取签证类型编码
def get_base_visa_type_code(id):
    if(id is None):
        return None
    opt = db.get_one("select name_en,code,code2 from " +
                     config.DB_PREFIX + "base_visa_type where id=" + str(id))
    if(opt is not None):
        return opt["code"]
    else:
        return None


# 获取签证类型英文名
def get_base_visa_type_name_en(id):
    if(id is None):
        return None
    opt = db.get_one("select name_en,code,code2 from " +
                     config.DB_PREFIX + "base_visa_type where id=" + str(id))
    if(opt is not None):
        return opt["name_en"]
    else:
        return ""


# 讲编码后的汉字转化为中文
def decode_unicode_chinese(text):
    if text:
        cc = text.decode("unicode_escape")
        text = cc.encode("UTF-8")
        return text
    else:
        return ""


# 删除文件
def delete_file(filename):
    try:
        os.remove(filename)
    except Exception:
        pass


# 生成PDF文件
def make_pdf_file(template, target, encodedjson):
    JAVA_COMMAND = config.config.get("BASE", "JAVA_COMMAND")
    FILL_PDF_JAR = config.config.get("BASE", "FILL_PDF_JAR")
    res = check_output([JAVA_COMMAND, "-jar", FILL_PDF_JAR, "--input",
                        template, "--output", target, "--data", encodedjson], stderr=STDOUT)
    return res


# list 从集合中根据给定的字典查找一条数据出来
def list_find_one(from_list, selector):
    # 若数据类型不对，则返回空
    if not isinstance(from_list, list) and not isinstance(from_list, tuple):
        return None
    if not isinstance(selector, dict):
        return None
    select_keys = selector.keys()
    res = None
    for i in range(0, len(from_list)):
        itm = from_list[i]
        is_ok = True
        for j in range(0, len(select_keys)):
            key_name = select_keys[j]
            key_value = selector[key_name]
            # 若没有该键，则不满足条件
            if not itm.has_key(key_name):
                is_ok = False
                break
            if isinstance(key_value, list):
                if itm[key_name] not in key_value:
                    is_ok = False
                    break
            elif isinstance(key_value, dict):
                my_key = key_value.keys()[0]
                if my_key == "neq":
                    if isinstance(key_value[my_key], list):
                        if itm[key_name] in key_value[my_key]:
                            is_ok = False
                            break
                    else:
                        if itm[key_name] == key_value[my_key]:
                            is_ok = False
                            break
            else:
                if itm[key_name] != key_value:
                    is_ok = False
                    break
        # 若所有条件都满足，则返回这条数据
        if is_ok:
            res = itm
    return res


# list 从集合中根据给定的字典查找所有的数据
def list_find_all(from_list, selector):
    # 若数据类型不对，则返回空
    if not isinstance(from_list, list) and not isinstance(from_list, tuple):
        return []
    if not isinstance(selector, dict):
        return []
    return_list = []
    select_keys = selector.keys()
    for i in range(0, len(from_list)):
        itm = from_list[i]
        is_ok = True
        for j in range(0, len(select_keys)):
            key_name = select_keys[j]
            key_value = selector[key_name]
            # 若没有该键，则不满足条件
            if not itm.has_key(key_name):
                is_ok = False
                break
            if isinstance(key_value, list):
                if itm[key_name] not in key_value:
                    is_ok = False
                    break
            elif isinstance(key_value, dict):
                my_key = key_value.keys()[0]
                if my_key == "neq":
                    if isinstance(key_value[my_key], list):
                        if itm[key_name] in key_value[my_key]:
                            is_ok = False
                            break
                    else:
                        if itm[key_name] == key_value[my_key]:
                            is_ok = False
                            break
            else:
                if itm[key_name] != key_value:
                    is_ok = False
                    break
        # 若所有条件都满足，则返回这条数据
        if is_ok:
            return_list.append(itm)
    return return_list


# 根据国家、省份、城市、街道来获取全地址
def get_full_address(country, province, city, addr):
    if city not in addr:
        addr += "," + city
    if province not in addr:
        addr += "," + province
    if isinstance(country, int) or isinstance(country, long):
        country = get_base_country_english_name(country)
    if country:
        addr += "," + country
    return addr


# 获取多长时间的文本
def get_how_long_text(from_date):
    try:
        days = (datetime.now().date() - from_date).days
        if days / 365 > 0:
            if days / 365 > 1:
                return str(days / 365) + " Years"
            else:
                return "One Year"
        elif days / 30 > 0:
            if days / 30 > 1:
                return str(days / 30) + "Months"
            else:
                return "One Month"
        elif days > 0:
            if days > 1:
                return str(days) + " Days"
            else:
                return "One Day"
        return ""
    except Exception:
        return ""


# 获取字段内容
def get_field_value(table_name, field_name, conditions={}):
    if conditions and not isinstance(conditions, dict):
        return ""
    sql = "select " + field_name + " from qdgcms_" + table_name
    sql_params = []
    if conditions:
        select_keys = conditions.keys()
        for i in range(0, len(select_keys)):
            key_name = select_keys[i]
            key_value = conditions[key_name]
            if i > 0:
                sql += " and "
            else:
                sql += " where "
            sql += key_name + "=%s"
            sql_params.append(key_value)
    md = db.get_one(sql, sql_params)
    if md:
        return md[field_name]
    else:
        return ""


# 获取所有的天数
def get_day_count(start, to):
    return (to - start).days + 1


# 获取商户配置值
def get_agent_config(agent_id, config_key):
    config = db.get_one(
        "select config_value from qdgcms_agent_config where is_use_default=0 and config_key=%s and (agent_id=0 or agent_id=%s) order by agent_id desc", (config_key, agent_id))
    if config:
        return config["config_value"]
    else:
        return ""


# 获取代填表人信息
def get_preparer(agent_id, parter_id, country_id):
    preparer = None
    if agent_id:
        preparer = db.get_one('select * from ' + config.DB_PREFIX +
                              'abroad_contact where contact_type=1 and country=%s and agent_id=%s order by id desc limit 1', (country_id, agent_id))
    if not preparer and parter_id:
        preparer = db.get_one('select * from ' + config.DB_PREFIX +
                              'abroad_contact where contact_type=1 and country=%s and agent_id=0 and parter_id=%s order by id desc limit 1', (country_id, parter_id))
    if not preparer:
        preparer = db.get_one('select * from ' + config.DB_PREFIX +
                              'abroad_contact where contact_type=1 and country=%s and agent_id=0 and parter_id=0 order by id desc limit 1', (country_id))
    return preparer


# 填写pdf文件
def fill_pdf_file(template, target, data, app_id, isUpper, isEditable=True, marginx=0, marginy=0):
    if isUpper:
        # 将所有的值转化为大写
        keys = data.keys()
        for j in range(0, len(keys)):
            # 若为None则设置为空字符串
            if data[keys[j]] == None:
                data[keys[j]] = ""
            if(data[keys[j]]):
                data[keys[j]] = data[keys[j]].upper()
    encodedjson = json.dumps(data)
    encodedjson = quote(encodedjson)
    JAVA_COMMAND = config.config.get("BASE", "JAVA_COMMAND")
    FILL_PDF_JAR = config.config.get("BASE", "FILL_PDF_JAR")
    editable = "true" if isEditable else "false"
    res = check_output([JAVA_COMMAND, "-jar", FILL_PDF_JAR, "--input", template, "--output", target,
                        "--data", encodedjson, "--canedit", editable, "--marginx", str(marginx), "--marginy", str(marginy)], stderr=STDOUT)
    if "SUCCESS" in res:
        log(app_id, "生存成功", res)
        return True
    else:
        log(app_id, "生存Pdf文件失败", res)
        return False


# 构造订单的流程
def make_app_work_flow(text, note, by='', nowData='', isInner=False, override=True):
    if nowData:
        try:
            nowData = json.loads(nowData)
        except Exception:
            nowData = []
    else:
        nowData = []
    count = len(nowData)
    data = {
        "by": by,
        "text": text,
        "note": note,
        "time": pub.get_now_time(),
        "inner": isInner
    }
    # 是否覆盖
    try:
        if override and nowData[count-1]["text"] == text and nowData[count-1]["note"] == note:
            nowData[count-1]["time"] = pub.get_now_time()
        else:
            nowData.append(data)
    except Exception:
        nowData.append(data)
    return json.dumps(nowData)


if __name__ == "__main__":
    t = get_now_time()
    t1 = time.strftime('%Y-%m-%d %H:%M:%S')
    t2 = get_now_times()
    print(t, t1, t2, sep="\n")
    print(t, t1, t2)